import matplotlib.pyplot as plt
import numpy as np
import random
import scipy.cluster.hierarchy as sch
from scipy.cluster.vq import vq, kmeans, whiten
from scipy import cluster
from scipy.cluster import hierarchy  # 用于进行层次聚类，话层次聚类图的工具包
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)

def HierarchicalClustering(dataIn, methodIn):
    # 1. 层次聚类
    # 生成点与点之间的距离矩阵,这里用的欧氏距离:
    disMat = sch.distance.pdist(dataIn, 'euclidean')
    # 进行层次聚类:
    Z = sch.linkage(disMat, method=methodIn, metric='euclidean')
    # 将层级聚类结果以树状图表示出来并保存为plot_dendrogram.png
    P = sch.dendrogram(Z)
    # plt.savefig('plot_dendrogram.png')
    # 根据linkage matrix Z得到聚类结果:
    label = cluster.hierarchy.cut_tree(Z, height=29)
    label = label.reshape(label.size)
    fig = plt.figure() 
    ax2 = fig.add_subplot(111)
    ax2.set_title(u'层次聚类效果二维图展示')
    plt.scatter(dataIn[:, 0], dataIn[:, 1], c=label, edgecolor='k')
    plt.show()

if __name__ == '__main__':
    df = pd.read_csv(r'Mall_Customers.csv')
    data = df.values
    rows = data.shape[0]
    cols = data.shape[1]
    print(rows,cols)
    dataUse = np.zeros((rows,2))
    for i,single in enumerate(data):
        dataUse[i,0] = single[2]
        dataUse[i,1] = single[4]
        pass
    HierarchicalClustering(dataUse, 'average')